import fs from 'fs';
import path from 'path';

export class Logger {
  private context: string;
  private logLevel: string;
  private logFile?: string;

  constructor(context: string = 'App') {
    this.context = context;
    this.logLevel = process.env.LOG_LEVEL || 'info';
    this.logFile = process.env.LOG_FILE;
    
    // 确保日志目录存在
    if (this.logFile) {
      const logDir = path.dirname(this.logFile);
      if (!fs.existsSync(logDir)) {
        fs.mkdirSync(logDir, { recursive: true });
      }
    }
  }

  private getTimestamp(): string {
    return new Date().toISOString();
  }

  private formatMessage(level: string, message: string, meta?: any): string {
    const timestamp = this.getTimestamp();
    const metaStr = meta ? ` ${JSON.stringify(meta)}` : '';
    return `[${timestamp}] [${level.toUpperCase()}] [${this.context}] ${message}${metaStr}`;
  }

  private shouldLog(level: string): boolean {
    const levels = ['debug', 'info', 'warn', 'error'];
    const currentLevelIndex = levels.indexOf(this.logLevel);
    const messageLevelIndex = levels.indexOf(level);
    return messageLevelIndex >= currentLevelIndex;
  }

  private writeLog(level: string, message: string, meta?: any): void {
    if (!this.shouldLog(level)) return;

    const formattedMessage = this.formatMessage(level, message, meta);
    
    // 控制台输出
    switch (level) {
      case 'debug':
        console.debug(formattedMessage);
        break;
      case 'info':
        console.info(formattedMessage);
        break;
      case 'warn':
        console.warn(formattedMessage);
        break;
      case 'error':
        console.error(formattedMessage);
        break;
    }

    // 文件输出
    if (this.logFile) {
      try {
        fs.appendFileSync(this.logFile, formattedMessage + '\n');
      } catch (error) {
        console.error('Failed to write to log file:', error);
      }
    }
  }

  debug(message: string, meta?: any): void {
    this.writeLog('debug', message, meta);
  }

  info(message: string, meta?: any): void {
    this.writeLog('info', message, meta);
  }

  warn(message: string, meta?: any): void {
    this.writeLog('warn', message, meta);
  }

  error(message: string, meta?: any): void {
    this.writeLog('error', message, meta);
  }

  log(level: string, message: string, meta?: any): void {
    this.writeLog(level, message, meta);
  }

  // 创建子logger
  child(context: string): Logger {
    return new Logger(`${this.context}:${context}`);
  }
}